package cn.tedu.sp11.filter;

import cn.tedu.web.util.JsonResult;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * 自定义zuul过滤器,只需要添加@Component
 */
@Component
public class AccessFilter extends ZuulFilter {
    //前置,后置,路由,错误处理
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;

    }

    //顺序号
    @Override
    public int filterOrder() {
        /**
         * 在zuul默认过滤器的第五个过滤器中,向context对象添加了service id
         * 在后面过滤器中才能访问 service id
         */
        return 6;
    }

    //针对当前这次请求,是否要执行过滤代码
    @Override
    public boolean shouldFilter() {
        /**
         * 如果请求商品,执行过滤
         * 如果请求用户或订单,跳过过滤
         */
        RequestContext ctx = RequestContext.getCurrentContext();
        //获取调用id
        String serviceId = (String) ctx.get(FilterConstants.SERVICE_ID_KEY);
        return "item-service".equalsIgnoreCase(serviceId);
    }

    //过滤代码,权限判断
    @Override
    public Object run() throws ZuulException {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();

        //接收token参数
        String token = request.getParameter("token");
        //如果没有token
        if (StringUtils.isBlank(token)) {
            //阻止继续访问
            ctx.setSendZuulResponse(false);

            //直接返回响应
            ctx.addZuulResponseHeader("Conten-type", "application/json");
            ctx.setResponseStatusCode(200);
            ctx.setResponseBody(
                    JsonResult.
                    err().
                    code(JsonResult.NOT_LOGIN).
                    msg("not login").
                    toString());
        }
        return null;//zuul当前版本 返回值不适用,没任何意义
    }
}
